package com.virtualmall.interceptor;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.virtualmall.bean.Account;
import com.virtualmall.common.Constants;
import com.virtualmall.service.AccountService;

public class AuthenticationInterceptor extends HandlerInterceptorAdapter {

    private List<String> doNotNeedSessionURLs;
    
	@Autowired
	private AccountService accountService;
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
            Object object) throws Exception {
        HttpSession session = request.getSession();
        
        if(session.getAttribute(Constants.USER_ID_SESSION) != null){
            return true;
        }
        
        //就简单判断了一下，如果要详细控制可以用spring security
        String url = request.getRequestURI();
        //读取userId和对应的key，如果是合法用户，则直接跳转
        String userId = request.getParameter("uid");
        String key = request.getParameter("key");
        
        try {
			if(StringUtils.isNotEmpty(userId)&&StringUtils.isNotEmpty(key)){
				Account account = this.accountService.read(Long.valueOf(userId));
				if(account!=null&&key.equals(account.getPassword())){
					Date lastLoginDate = account.getLastLoginDate();

			        account.setOnlineStatus(Constants.ACCOUNT_STATUS_ONLINE);
			        account.setLastLoginDate(new Date());
			        this.accountService.update(account);

			        account.setPassword(null);
			        
			        request.getSession().setAttribute(Constants.USER_ID_SESSION, account.getId());
			        request.getSession().setAttribute(Constants.USER_ACCOUNT_SESSION, account);
			        request.getSession().setAttribute(Constants.USER_LAST_LOGIN_DATE, lastLoginDate);
			        
					return true;
				}
			}
		} catch (Exception e) {
	        response.sendRedirect(request.getContextPath()); 
	        
			return false;
		}
        
        for(String doNotNeedSessionURL : doNotNeedSessionURLs){
            if(url.matches(doNotNeedSessionURL)){
                return true;
            }
        }
        
        response.sendRedirect(request.getContextPath()); 
        
        return false;
        
    }

    public void setDoNotNeedSessionURLs(List<String> doNotNeedSessionURLs) {
        this.doNotNeedSessionURLs = doNotNeedSessionURLs;
    }
}
